package io.gitee.zhucan123.core.infrastructure.entity;


import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

/**
 * @author: zhuCan
 * @date: 2019/10/11 10:50
 * @description:
 */
@NoArgsConstructor
@Builder
@Data
@AllArgsConstructor
public class PageSort {

  /**
   * 当前页
   */
  @Builder.Default
  private Integer pageNum = 0;

  /**
   * 每页数
   */
  @Builder.Default
  private Integer pageSize = 10;

  /**
   * 排序
   */
  @Builder.Default
  private Sort sort = Sort.DESC;

  /**
   * 需要排序的字段
   */
  @Builder.Default
  private String[] sortProperties = new String[]{"createdAt"};

  private org.springframework.data.domain.Sort.Direction getSort() {
    if (sort == Sort.DESC) {
      return org.springframework.data.domain.Sort.Direction.DESC;
    } else {
      return org.springframework.data.domain.Sort.Direction.ASC;
    }
  }

  /**
   * 转为 pageable对象
   *
   * @return
   */
  public Pageable getPageable() {

    //带排序,并且有分页字段
    if (sort != null && sortProperties != null && sortProperties.length > 0) {
      return PageRequest.of(pageNum, pageSize, getSort(), sortProperties);
    }

    //带排序但没有字段
    if (sort != null) {
      return PageRequest.of(pageNum, pageSize, getSort(), "createdAt");
    }
    //默认不带排序
    return PageRequest.of(pageNum, pageSize);
  }

  public Integer getPageNum() {
    return pageNum;
  }

  public void setPageNum(Integer pageNum) {
    this.pageNum = pageNum;
  }
}
